# coding:utf-8
class Admin::AdvertiseGroupsController < AdminController

  respond_to :html, :json
  before_filter :setup, only: [:index, :show]
  set_tab :business

  def index
    set_tab :recruitment_groups, :sub_nav
    @advertise_groups = AdvertiseGroup.includes(:province_advertise_rules,:city_advertise_rules,:terminal_group_advertise_rules).order('created_at desc').page params[:page]
  end

  def new
    @advertise_group = AdvertiseGroup.new
  end

  def show
    @advertise_group = AdvertiseGroup.find params[:id]
    @ways << @advertise_group.name
    set_tab :recruitment_groups, :sub_nav
  end

  def edit
    @advertise_group = AdvertiseGroup.find params[:id]
  end

  def create
    @advertise_group = AdvertiseGroup.new params[:advertise_group]
    render action: :edit unless @advertise_group.save
  end

  def update
    @advertise_group = AdvertiseGroup.find params[:id]
    render :action => :edit unless @advertise_group.update_attributes params[:advertise_group]
  end

  def destroy
    @advertise_group = AdvertiseGroup.find params[:id]
    @advertise_group.destroy
  end

  def rules
    @advertise_group = AdvertiseGroup.find params[:id]
  end

  def update_rules
    @advertise_group = AdvertiseGroup.find params[:id]
    params[:rules].each_pair do |ruleable,value|
      if ruleable.match(/(.+)_(\d+)/)
        advertise_ruleable_type,advertise_ruleable_id = $1.classify, $2
        advertise_rule = AdvertiseRule.where(advertise_ruleable_type: advertise_ruleable_type,
          advertise_ruleable_id: advertise_ruleable_id).first
        case value
        when "0"
          if advertise_rule.advertise_group_id == @advertise_group.id
            advertise_rule.update_attributes(advertise_group_id: nil)
          end
        when "1"
          unless advertise_rule.advertise_group_id == @advertise_group.id
            advertise_rule.update_attributes(advertise_group_id: @advertise_group.id)
          end
        end
      end
    end
  end

  private

  def setup
    @ways = ["业务","广告投放管理"]
    @left_panel = "layouts/account_widget"
  end

end